﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Gype.UI;
using SKYPE4COMLib;
using SlimDX;

namespace Gype.GUI.Components
{
    public class ContactEntry : Component
    {
        public ContactEntry(User contact)
        {
            mContact = contact;
            mUserName = contact.FullName;
            if (string.IsNullOrEmpty(mUserName))
                mUserName = contact.Handle;

            mOnlineStatus = contact.OnlineStatus;
        }

        internal override void RenderObject()
        {
        }

        internal override void RenderTopLevel()
        {
        }

        internal void RenderObject(Vector2 location)
        {
            if (mTarget == null)
                return;

            mTarget.FillRoundedRectangle(new Vector2(location.X + 1, location.Y + 1), new Vector2(Size.Width - 2, Size.Height - 2), 4, 4, BrushCollection.ContactListBackground);
            if (IsHovered)
                mTarget.FillRoundedRectangle(new Vector2(location.X + 1, location.Y + 1), new Vector2(Size.Width - 2, Size.Height - 2), 4, 4, BrushCollection.ContactListItemSelect);

            Image img = null;
            if (ImageCollection.OnlineImageList.ContainsKey(mOnlineStatus))
                img = ImageCollection.OnlineImageList[mOnlineStatus];
            else
                img = ImageCollection.OnlineImageList[TOnlineStatus.olsUnknown];

            mTarget.DrawImage(img, new System.Drawing.RectangleF(location.X + 3, location.Y + 2, 16, 16));
            mUserNameText.DrawText(mUserName, new Vector2(location.X + 25, location.Y + 3), new Vector2(Size.Width - 2 - 25, 14));
        }

        internal void DrawTopLevel(Vector2 location)
        {
            if (mInfoPopup.UserAvatar == null)
                loadInfoPopupAsync();

            mInfoPopup.Render(new Vector2(location.X + Size.Width - 2 - 7, location.Y + (Size.Height - 2) / 2.0f), false);
        }

        private void loadInfoPopupAsync()
        {
            lock (mInfoPopup)
                mInfoPopup.UserAvatar = ImageCollection.DefaultAvatar;

            System.Threading.Thread t = new System.Threading.Thread(() =>
                {
                    Image img = getAvatarImage();
                    if (img == null)
                        img = ImageCollection.DefaultAvatar;

                    lock (mInfoPopup.LockObject)
                        mInfoPopup.UserAvatar = img;
                }
            );

            t.Start();
        }

        internal override void AttachedToManager(Manager mgr)
        {
            mGUIManager = mgr;
            mTarget = mgr.Target;

            mUserNameText = new TextElement(TextCollection.Arial);
            mUserNameText.Alignment = TextAlignement.Left;
            mUserNameText.Color = BrushCollection.TabHeaderTextSelect;

            mInfoPopup.UserFriendlyName = mUserName;
            mInfoPopup.User = mContact;
            mInfoPopup.attachToTarget(mgr.Target);
            
        }

        internal Image getAvatarImage()
        {
            string tmpAvatarFile = System.IO.Path.GetTempFileName();
            tmpAvatarFile = System.IO.Path.GetFullPath(tmpAvatarFile);

            System.IO.File.Delete(tmpAvatarFile);
            tmpAvatarFile = System.IO.Path.GetDirectoryName(tmpAvatarFile) + "\\" + System.IO.Path.GetFileNameWithoutExtension(tmpAvatarFile) + ".jpg";

            Command cmd = new Command();
            cmd.Command = "GET USER " + mContact.Handle + " AVATAR 1 " + tmpAvatarFile;
            cmd.Blocking = true;
            cmd.Timeout = 2000;

            mGUIManager.SkypeInterface.SendCommand(cmd);

            try
            {
                DateTime start = DateTime.Now;
                while ((DateTime.Now - start).TotalSeconds < 2.0f)
                {
                    try
                    {
                        System.IO.File.Open(tmpAvatarFile, System.IO.FileMode.Append).Close();
                        System.IO.FileInfo fi = new System.IO.FileInfo(tmpAvatarFile);
                        if (fi.Length > 0)
                            break;
                    }
                    catch (Exception)
                    {
                    }
                }

                System.Drawing.Image img = System.Drawing.Image.FromFile(tmpAvatarFile);
                Image ret = null;
                mGUIManager.Dispatcher.Invoke(() => { ret = Image.FromGDI(mTarget, (System.Drawing.Bitmap)img); });
                img.Dispose();
                System.IO.File.Delete(tmpAvatarFile);
                return ret;
            }
            catch (Exception)
            {
                try
                {
                    System.IO.File.Delete(tmpAvatarFile);
                }
                catch (Exception)
                {
                }
                return null;
            }            
        }

        public TOnlineStatus OnlineStatus { get { return mOnlineStatus; } }
        public string ContactName { get { return mUserName; } }

        internal bool IsHovered = false;

        private string mUserName;
        private TOnlineStatus mOnlineStatus;
        private TextElement mUserNameText;
        private ContactPopup mInfoPopup = new ContactPopup();
        Rendertarget mTarget;
        User mContact;
    }
}
